/*
 * @Author: 徐建辰
 * @Date: 2022-05-30 10:27:35
 * @LastEditTime: 2022-05-30 10:27 10:27:39
 * @LastEditors: 徐建辰
 * @Description: 原生xhr请求封装
 */
export default function xhrRequest(options) {
  return new Promise((resolve, reject) => {
    options = options || {}
    options.method = options.method ? options.method.toUpperCase() : 'GET'
    options.dataType = options.dataType || 'json'
    options.data = options.data || {}

    const params = formatParams(options.data)
    let xhr

    if (window.XMLHttpRequest) {
      xhr = new XMLHttpRequest()
    } else if (window.ActiveObject) { // 兼容IE6以下版本
      xhr = new ActiveXobject('Microsoft.XMLHTTP')
    }

    if (options.method === 'GET') {
      xhr.open('GET', `${options.url}?${params}`, true)
      xhr.send(null)
    } else if (options.method === 'POST'){
      xhr.open('post', options.url, true)
      xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded')
      xhr.send(params);
    }

    const timer = setTimeout(() => {
      if (xhr.readySate !== 4) {
        xhr.abort()
      }
      clearTimeout(timer)
    }, options.timeout)

    xhr.onreadystatechange=function(){
      if (xhr.readyState === 4){
        var status = xhr.status
        if (status === 200) {
          resolve(JSON.parse(xhr.responseText))
        } else {
          console.log('error:xhr.status =', status)
          reject(xhr)
        }
      }
    }
  })
}

//格式化请求参数
function formatParams(data) {
  var arr = []
  for (var name in data){
    arr.push(encodeURIComponent(name) + '=' + encodeURIComponent(data[name]))
  }
  arr.push(('v=' + Math.random()).replace('.', ''))
  
  return arr.join('&')
}